package com.lbb.springbootstock.service;

import com.alibaba.fastjson.JSON;
import com.lbb.springbootstock.bean.Stock;
import com.lbb.springbootstock.client.HttpClient;
import com.lbb.springbootstock.client.JdbcUtil;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 获取股票列表服务类
 **/
public class StockListService {
    public final static String PAGE_NO = "1";
    public final static String PAGESIZE = "5000";
    public final static String URL = "https://hq.techgp.cn/rjhy-gmg-quote/api/1/stock/quotes/shszstocksort?en_hq_type_code=XSHG.ESA%2CXSHE.ESA%2CXSHG.KSH&sort_field_name=px_change_rate&sort_type=1&pageNo=" + PAGE_NO + "&pageSize=" + PAGESIZE;

    public static void getStockList() throws SQLException {
        System.out.println("URL: "+URL);
        String result = HttpClient.doPost(URL);
        int start = result.indexOf("[");
        int end =result.indexOf("]")+1;
        result =result.substring(start,end);
        System.out.println(result);
        List<Stock> stocks = JSON.parseArray(result, Stock.class);
        SimpleDateFormat format =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        stocks.stream().forEach(item->item.setCreateTime(format.format(new Date())));
        save(stocks);
    }
    public static void save(List<Stock> stocks) throws SQLException {
        Connection connection = JdbcUtil.getConnection();
        PreparedStatement ps = connection.prepareStatement(
                "INSERT into stock(`id`,`Market_Symbol`,`Prod_name`,`Last_px`,`Open_px`,`High_px`,`Low_px`,`Preclose_px`,`Business_amount`,`Amplitude`,`Business_balance`,`Market_value`,`Vol_ratio`,`Exchange_Symbol`,`createTime`) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)" );
        for(Stock item :stocks){
            ps.setString(1,item.getId());
            ps.setString(2,item.getMarket_Symbol());
            ps.setString(3,item.getProd_name());
            ps.setString(4,item.getLast_px());
            ps.setString(5,item.getOpen_px());
            ps.setString(6,item.getHigh_px());
            ps.setString(7,item.getLow_px());
            ps.setString(8,item.getPreclose_px());
            ps.setString(9,item.getBusiness_amount());
            ps.setString(10,item.getAmplitude());
            ps.setString(11,item.getBusiness_balance());
            ps.setString(12,item.getMarket_value());
            ps.setString(13,item.getVol_ratio());
            ps.setString(14,item.getExchange_Symbol().toUpperCase());
            ps.setString(15,item.getCreateTime().toString());
            ps.addBatch();
        }
        ps.executeBatch();
    }

    public static void main(String[] args) throws SQLException {
        getStockList();
    }
}
